package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.colliery.common.ext.gone
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.report
import com.spark.common.ext.wrapIO
import com.spark.common.model.db.HTSubmitDetailModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.trouble.R
import com.spark.trouble.model.ChkStdModel
import kotlinx.android.synthetic.main.frag_selector_chk_std.*

/**
 * 考核标准 && 选择危险源
 */
class ChkStdFragment : BaseFragment() {
    private var directSelect: DirFilterDF? = null
    private var keywordSelect: KeywordFilterDF? = null
    private lateinit var chkStdAdapter: ChkStdAdapter

    private var selectedPos = -1
    private var dir: String = ""
    private var keyword: String = ""
    // 是否显示统计布局
    private var singleChoice = false
    // 类型 0： 考核标准
    //     1: 危险
    private var type = 0

    companion object {
        val resCodeStdChk = 0x0001
        val resCodeDangerSource = 0x0002

        fun newInstance(singleChoice: Boolean, type: Int): ChkStdFragment {
            val chkStdFragment = ChkStdFragment()
            val args = Bundle()
            args.apply {
                putBoolean("singleChoice", singleChoice)
                putInt("type", type)
            }
            chkStdFragment.arguments = args
            return chkStdFragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_selector_chk_std
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        iv_back.setOnClickListener { pop() }


        arguments?.apply {
            singleChoice = getBoolean("singleChoice", false)
            this@ChkStdFragment.type = getInt("type", 0)
        }
        tv_title.text = if (type == 0) "选择考核标准" else "选择危险源"
        rl_summary.gone(singleChoice)

        tv_directory.setOnClickListener {
            selectedPos = 0
            directSelect = DirFilterDF.newInstance(object : OnFilterSelectListener {
                override fun onFilterChecked(keyword: String) {
                    dir = keyword
                    LogUtils.e("【dir】$dir")
                }
            })
            directSelect?.showNow(childFragmentManager, "directory")
            keywordSelect?.dismiss()
            updateSelectState(selectedPos)
        }
        tv_keyword.setOnClickListener {
            selectedPos = 1
            keywordSelect = KeywordFilterDF.newInstance(object : OnFilterSelectListener {
                override fun onFilterChecked(keyword: String) {
                    this@ChkStdFragment.keyword = keyword
                    LogUtils.e("【keyword】$keyword")
                }
            })
            keywordSelect?.showNow(childFragmentManager, "keyword")
            directSelect?.dismiss()
            updateSelectState(selectedPos)
        }
        refresh_layout.apply {
            setOnRefreshListener { }
            setOnLoadmoreListener { }
        }
        chkStdAdapter = ChkStdAdapter(R.layout.item_selector, singleChoice).apply {
            setOnItemClickListener { adapter, view, position ->
                if (singleChoice) {
                    val data = chkStdAdapter.data[position]
                    val bundle = Bundle()
                    bundle.putString("chkstd", Gson().toJson(data))
                    setFragmentResult(resCodeStdChk, bundle)
                    pop()
                } else {
                    updateChkState(position)
                }
            }
            addCountChangeListener(object : OnCoundChangeListener {
                override fun onCountChanged() {
                    val size = chkStdAdapter.summary().size
                    tv_selected_count.text = "$size"
                }
            })
        }
        recy_stds.apply {
            adapter = chkStdAdapter
            layoutManager = LinearLayoutManager(context)
        }

        tv_sure.setOnClickListener {
            val submitChilds = mutableListOf<HTSubmitDetailModel>()
            chkStdAdapter.summary().forEach {
                val child = HTSubmitDetailModel(
                        sourceDesc = it.description,
                        sourceId = it.sourceId.toString(),
                        sourceprocessorId = it.processor_id.toString(),
                        sourceMoney = it.money.toString(),
                        sourceScore = it.score.toString(),
                        troubleContent = it.keyName
                )
                submitChilds.add(child)
            }
            val bundle = Bundle()
            bundle.putString("chkstds", Gson().toJson(submitChilds))
            setFragmentResult(resCodeDangerSource, bundle)
            pop()
        }
        updateSelectState(selectedPos)
        fetchChkStds()
    }

    private fun updateSelectState(selectedPos: Int) {
        tv_directory.apply {
            if (selectedPos == 0) {
                setTextColor(resources.getColor(R.color.blue0092))
                setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_up_blue, 0)
            } else {
                setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_down, 0)
                setTextColor(resources.getColor(R.color.black))
            }

        }
        tv_keyword.apply {
            if (selectedPos == 1) {
                setTextColor(resources.getColor(R.color.blue0092))
                setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_up_blue, 0)
            } else {
                setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_down, 0)
                setTextColor(resources.getColor(R.color.black))
            }

        }
    }


    @SuppressLint("CheckResult")
    private fun fetchChkStds() {
        val params = mutableMapOf(
                Pair("clauseFolderId", ""),
                Pair("clausekeyword", "")
        )
        val url = if (type == 0) "${Const.base_url}${Const.act_chk_std_selector}" else "${Const.base_url}${Const.act_ht_std_selector}"
        Http.request()
                .rxPost(url, params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ChkStdModel::class.java)?.apply {
                                if (code == "200") {
                                    chkStdAdapter.addData(resultMaps)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }
}

class ChkStdAdapter(layoutRes: Int, var singleChoice: Boolean) : BaseQuickAdapter<ChkStdModel.ResultMap, BaseViewHolder>(layoutRes) {
    private var onCoundChangeListener: OnCoundChangeListener? = null

    override fun convert(helper: BaseViewHolder?, item: ChkStdModel.ResultMap?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_level, item.keyName)
            setText(R.id.tv_standard, item.description)
            getView<ImageView>(R.id.iv_plus).apply {
                gone(singleChoice)
                setOnClickListener {
                    item.isChecked = true
                    onCoundChangeListener?.onCountChanged()
                }
            }
        }
    }

    fun updateChkState(position: Int) {
        data[position].isChecked = true
        onCoundChangeListener?.onCountChanged()
    }

    fun addCountChangeListener(listener: OnCoundChangeListener) {
        onCoundChangeListener = listener
    }

    fun summary(): MutableList<ChkStdModel.ResultMap> {
        return data.filter {
            return@filter it.isChecked
        }.toMutableList()
    }
}

interface OnCoundChangeListener {
    fun onCountChanged()
}